<route lang="yaml">
  meta:
    title: 商品管理
  </route>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'

interface Product {
  productId: number
  productName: string
  supplier: string
  type: string
  size: string
  weight: string
  price: string
  status: '在售' | '停售'
}

// 表格数据
const tableData = ref<Product[]>([
  {
    productId: 1,
    productName: '智能手机X1',
    supplier: '华为科技',
    type: '电子产品',
    size: '6.7英寸',
    weight: '75mm',
    price: '5999.00',
    status: '在售',
  },
  {
    productId: 2,
    productName: '无线耳机Pro',
    supplier: '小米生态',
    type: '音频设备',
    size: '50mm',
    weight: '20mm',
    price: '399.00',
    status: '停售',
  },
])

// 弹窗控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)

// 表单引用
const addFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

// 表单数据
const addFormData = reactive<Omit<Product, 'productId'>>({
  productName: '',
  supplier: '',
  type: '',
  size: '',
  weight: '',
  price: '',
  status: '在售',
})

const editFormData = reactive<Product>({
  productId: 0,
  productName: '',
  supplier: '',
  type: '',
  size: '',
  weight: '',
  price: '',
  status: '在售',
})

// 商品分类选项
const typeOptions = [
  { value: '电子产品', label: '电子产品' },
  { value: '家居用品', label: '家居用品' },
  { value: '服装配饰', label: '服装配饰' },
]

// 验证规则
const rules = reactive({
  productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  supplier: [{ required: true, message: '请输入供应商', trigger: 'blur' }],
  type: [{ required: true, message: '请选择分类', trigger: 'change' }],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效金额', trigger: 'blur' },
  ],
})

// 新增商品
function handleAdd() {
  addFormRef.value?.resetFields()
  addDialogVisible.value = true
}

// 编辑商品
function handleEdit(row: Product) {
  Object.assign(editFormData, row)
  editDialogVisible.value = true
}

// 删除商品
async function handleDelete(row: Product) {
  try {
    await ElMessageBox.confirm(
      `确定删除商品【${row.productName}】吗？`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    const index = tableData.value.findIndex(item => item.productId === row.productId)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }
  catch {
    // 取消删除
  }
}
const searchKeyword = ref<string>('')
const selectedType = ref<string>('')
// 提交新增
function submitAdd() {
  addFormRef.value?.validate((valid) => {
    if (valid) {
      const newId = tableData.value.length
        ? Math.max(...tableData.value.map(p => p.productId)) + 1
        : 1

      tableData.value.push({
        productId: newId,
        ...addFormData,
      })
      addDialogVisible.value = false
      ElMessage.success('新增成功')
    }
  })
}

// 提交编辑
function submitEdit() {
  editFormRef.value?.validate((valid) => {
    if (valid) {
      const index = tableData.value.findIndex(item => item.productId === editFormData.productId)
      if (index > -1) {
        tableData.value.splice(index, 1, { ...editFormData })
        editDialogVisible.value = false
        ElMessage.success('修改成功')
      }
    }
  })
}
</script>

<template>
  <div>
    <FaPageMain>
      <div class="mb-4 flex justify-between">
        <div class="button-group">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            <span class="ml-1">新增</span>
          </el-button>
        </div>

        <div class="search-wrapper">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select
            v-model="selectedType"
            placeholder="商品分类"
            style="width: 200px;"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>

      <div class="table-wrapper">
        <el-table
          :data="tableData"
          style="width: 100%;"
          max-height="calc(100vh - 200px)"
        >
          <el-table-column prop="productId" label="商品ID" />
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="supplier" label="供应商" />
          <el-table-column prop="type" label="分类" />
          <el-table-column prop="size" label="尺寸" />
          <el-table-column prop="weight" label="重量(kg)" width="120" />
          <el-table-column prop="price" label="价格（元）" />
          <el-table-column prop="status" label="状态" />
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <div class="flex items-center">
                <el-button type="primary" link @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-wrapper">
        <el-pagination
          :page-size="20"
          :pager-count="11"
          layout="prev, pager, next"
          :total="tableData.length"
        />
      </div>
    </FaPageMain>

    <!-- 新增弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增商品"
      width="600px"
    >
      <el-form
        ref="addFormRef"
        :model="addFormData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="addFormData.productName" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="addFormData.supplier" />
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <el-select v-model="addFormData.type" placeholder="请选择">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="尺寸">
          <el-input v-model="addFormData.size" placeholder="示例：6.7英寸" />
        </el-form-item>
        <el-form-item label="重量">
          <el-input v-model="addFormData.weight" placeholder="示例：75mm" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="addFormData.price" placeholder="0.00">
            <template #append>
              元
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="addFormData.status">
            <el-option label="在售" value="在售" />
            <el-option label="停售" value="停售" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitAdd">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑商品"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editFormData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="editFormData.productId" disabled />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="editFormData.productName" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="editFormData.supplier" />
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <el-select v-model="editFormData.type">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="尺寸">
          <el-input v-model="editFormData.size" />
        </el-form-item>
        <el-form-item label="重量">
          <el-input v-model="editFormData.weight" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="editFormData.price">
            <template #append>
              元
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editFormData.status">
            <el-option label="在售" value="在售" />
            <el-option label="停售" value="停售" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitEdit">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.search-wrapper {
  display: flex;
  gap: 12px;
}

.table-wrapper {
  margin-top: 16px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
